// 防抖
/* 
简而言之就是 停止触发事件的n段时间之后才真正执行事件
*/

// l1
function debounce(fn, wait, immediate) {
	let time, res
	let debouced = function() {
		time && clearTimeout(time)
		let args = arguments
		if (immediate) {
			let now = !time
			time = setTimeout(() => {
				console.log('重置time')
				time = null
			}, wait)
			console.log('now:', now)
			if (now) {
				res = fn.apply(this, args)
			}
		} else {
			time = setTimeout(() => fn(args), wait)
		}
		return res
	}
	debouced.cancel = function() {
		// 取消
		clearTimeout(time)
		time = null
	}
	return debouced
}

function ql(x) {
	console.log(`${x}的平方是${x * x}`)
}
let lfn = debounce(ql, 2000, true)
let start = setInterval(() => {
	lfn(Math.floor(Math.random() * 10))
}, 500)

setTimeout(() => {
	clearInterval(start)
	console.log('结束了')
}, 10000)

// 节流
/* 
就是一段时间只触发一次
*/

function throttle(fn, wait) {
	let context, args
	let previos = 0

	return function() {
		let now = +new Date()
		context = this
		args = arguments
		if (now - previos > wait) {
			fn.apply(context, args)
			previos = now
		}
	}
}
